
import 'package:flutter/material.dart';
import '../../utils/Global.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../../provider/UserProvider.dart';

class CourseDetail extends StatefulWidget {
  final int id;
  final String title;
 

  // CourseDetail({Key? key,  required this.id, required this.title}): super(key: key);
  CourseDetail({Key? key, required this.id, required this.title}): super(key: key);
  // ignore: recursive_getters
  int get getId => id;
  
  @override
  // ignore: no_logic_in_create_state
  State<CourseDetail> createState() => _CourseDetailState(id);
}

class _CourseDetailState extends State<CourseDetail> {
  Map<String?, dynamic> course = {
    'courseName': '',
    'courseImgUrl': '',
    'sales': '',
    'price': '',
    'oldPrice': '',
    'teacherDTO': {
      'teacherName': ''
    }
  };
  Map<String?,  dynamic> section = {
    // "courseSectionList": [{"sectionName": '', "courseLessons": {'theme': '', 'canPlay': ''}}]
  };
  int detailId = 0;
  _CourseDetailState(int id) {
    detailId = id;
  }
  // tab菜单
  final List<Widget> _tabs = [
    Tab(text: "详情"),
    Tab(text: "目录"),
  ];
  String pic = "http://192.168.2.135:3000/3.jpg";
  List<Widget> _tabViews = [];
  int len = 0;
  @override
  void initState() {
    // print('$widget, 打印组件内容');
    G.api.course.courseDetail(id: widget.id).then((dynamic value) {
      setState(() {
        for(int i = 0; i < value.length; i++) {
          if(value[i]['id']  == detailId) {
            course = value[i]!;
            break;
          }
        }
      });
    });

    G.api.course.courseSection(id: widget.id).then((dynamic value) {
      setState(() {
        
        for(int i = 0; i < value.length; i++) {
          if(value[i]['id']  == detailId) {
            section = value[i]!;
            if(section['courseSectionList'] != null) {
              for(int k = 0; k < section['courseSectionList'].length; k++) {
                len += section['courseSectionList'][k]['courseLessons'].length as int;
              }
            }
            break;
          }
        }
      });
    });
    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    UserProvider userProvider = Provider.of<UserProvider>(context);

    _tabViews = [
      HtmlWidget(
        course['courseDescription']?? '',
        customStylesBuilder: (element) {
          if (element.classes.contains('foo')) {
            return {'color': 'red'};
          }
          return null;
        },
        renderMode: RenderMode.column,
        textStyle: const TextStyle(fontSize: 14.0),
      ),
      renderCourseSection()
    ];
    
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Column(
        children: [
          Image.network(
            course['courseListImg'] ?? pic,
            fit: BoxFit.cover,
            height: 200,
          ),
          
          Container(
            padding: const EdgeInsets.fromLTRB(16, 20, 16, 10),
            height: 140,
            child:  Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  width: double.infinity,
                  child: Text(
                    course['courseName'] ?? '',
                    style: const TextStyle(
                      fontSize: 16,
                    ),
                  ),
                ),
                SizedBox(
                  width: double.infinity,
                  child: Text(
                    course['brief'] ?? '',
                    style: const TextStyle(
                      fontSize: 14,
                      
                    ),
                  ),
                ),
                Row(children: [
                  Container(
                    color: Colors.grey[200],
                    padding: const EdgeInsets.all(5),
                    child: Text(
                      course['teacherDTO']!['teacherName'] ?? ''
                    ),
                  ),
                ],),
                Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween, 
                children: [
                  Container(
                    child: Text(
                      '¥${course['price'] ?? 0 }',
                      style: const TextStyle(
                        fontSize: 14.0,
                        color: Colors.red ,
                        // fontWeight: FontWeight.w500
                      ),
                    ),
                  ),
                  Container(
                    child: Text(
                      '¥${course['oldPrice'] ?? 0}',
                      style: const TextStyle(
                        fontSize: 14.0,
                        color: Colors.grey,
                        decoration: TextDecoration.lineThrough,
                        // fontWeight: FontWeight.w500
                      ),
                    ),
                  ),
                  const SizedBox(width: 10),
                  Container(
                    child: Text(
                      '${course['sales'] ?? 0}人购买',
                      style: const TextStyle(
                        fontSize: 12.0
                      ),
                    ),
                  )
                ],)
              ],
            ),
          
        ),
        // 展示详情与章节
        Container(
          width: double.infinity,
          // height: double.maxFinite,
          // height: section['courseSectionList']![0]['courseLessons'].length!! * 60.0 * 2,
          height: len * 60.0,
            child: DefaultTabController(
            length: _tabs.length,
            child: Column(
              children: [
                TabBar(
                  tabs: _tabs,
                  labelColor: Colors.blue,
                  unselectedLabelColor: Colors.black,
                  indicatorSize: TabBarIndicatorSize.label,
                ),
                Expanded(
                  child: TabBarView(
                    children: _tabViews,
                  )
                )
                
              ],
            )),
          ),
          
        ],
      ),

      ),
      bottomNavigationBar: Row(
        children: [
          InkWell( // a标签
            onTap: () {
              Map<String, dynamic> p = {
                  'id': course['id'],
                  'title': course['courseName'] 
                };
                print('$p 梅西');
                G.router?.navigateTo(context, '/pay' + G.parseQuery(params: p));
                return;
              if(userProvider.isLogin == true) {
                Map<String, dynamic> p = {
                  'id': course['id'],
                  'title': course['courseName'] 
                };
                G.router?.navigateTo(context, '/pay' + G.parseQuery(params: p));
              } else {
                G.router?.navigateTo(context, '/login');
              }
              
            },
            child: Container(
              child: Text('立即购买',
              style: TextStyle(
                color: Colors.white,
                fontSize: 30.sp
                
                ),
              ),
              alignment: Alignment.center,
              width: 375.w,
              height: 100.h,
              color: Colors.green,
            ),
          ),
          InkWell( // a标签
            onTap: () {

            },
            child: Container(
              child: Text('砍价一元',
              style: TextStyle(
                color: Colors.white,
                fontSize: 30.sp
                
                ),
              ),
              alignment: Alignment.center,
              width: 375.w,
              height: 100.h,
              color: Colors.pink,
            ),
          )
        ],
      ),
    );
  }
  Widget renderCourseSection() {
    // List<Map<String?, dynamic>> ss = [{"theme": '', "canPlay": ''}];
    return Column(
      children: section['courseSectionList'] != null
       ? section['courseSectionList'].map<Widget>((module) {
        return Column(
          children: [
            ListTile(
              title: Text(
                module['sectionName']! ?? '',
                style: TextStyle(
                  height: 2.0,
                  fontSize: 15,
                  fontWeight: FontWeight.w500
                ),
              ),
            ),
            Column(
              children: module['courseLessons'] != null ?
                module['courseLessons'].map<Widget>((subsection) {
                  return Container(
                      height: 30,
                      child: ListTile(
                      onTap: (){

                      },
                      title: Text(subsection['theme']! ?? ''),
                      trailing: subsection['canPlay'] ?
                      Icon(Icons.play_circle_outline) : 
                      Icon(Icons.lock, color: Colors.grey[400],),
                    ),
                  );
                }).toList() :
                [],
            )
          ],
        );
       }).toList()
       : [Text('没有内容')]
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}